<?php

namespace App\Http\Controllers\API;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
use Event;
use App\Events\debug\Debug;
use App\Events\log\AllLog;
use App\Events\noti\Inform;
use App\Models\Area;
use App\Models\Building;
use App\Models\Room;
use Cache;

use Storage;

class LoraController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
/*        '{
            "hd":{
                "ver":"0",
                "rdTk":"1234",
                "pktp":0,
                "gwad":"T6CN470S0019"
            },
            "rxpk":{
                "time":"2018-01-25T16:56:13.687021Z", //时间
                "tmst":"1516870573", //时间戳
                "freq":472.9,
                "datr":"SF12BW125",
                "rssi":"-93.0",
                "lsnr":"0.8",
                "chan":7,
                "mote":{
                    "DevE":"0000000000000391",
                    "DevA":913,
                    "AppE":"BB02000000AB0000",
                    "fcnt":626,
                    "fprt":2,
                    "fmtp":2,
                    "data":"+hZMSDA1MTQxMDAwMDAwMDAwMzkxEAD8",
                    "datar":"fa164c4830353134313030303030303030303339311000fc"
                }
            },
            "action":"app_data"
        }'*/
        // $data = [
        //     'hd'=>[
        //         'ver'=>'0',
        //         'rdTk'=>'1234',
        //         'pktp'=>0,
        //         'gwad'=>"T6CN470S0019" //
        //     ],
        //     'rxpk'=>[
        //         'time'=>'2018-01-25T16:56:13.687021Z', //
        //         'tmst'=>'1516870573', //
        //         'freq'=>472.9, //
        //         'datr'=>'SF12BW125', //
        //         'rssi'=>'-93.0', //
        //         'lsnr'=>'17.9', //
        //         'chan'=>7, //
        //         'mote'=>[
        //             'DevE'=>'0000000000000391', //
        //             'DevA'=>913,
        //             'AppE'=>'BB02000000AB1111', //
        //             'fcnt'=>626, //
        //             'fprt'=>2, //
        //             'fmtp'=>2,
        //             'data'=>'+hZMSDA1MTQxMDAwMDAwMDAwMzkxEAD8',
        //             // 'datar'=>'b18001ff0000e1' //
        //             'datar'=>'fa164c483035313431303030303030303030333931ff00fc' //
        //         ]
        //     ],
        //     'action'=>'app_data'
        // ];
        // $rxpk = $data['rxpk'];


        $data = $request->all();
        $rxpk = $request->input('rxpk'); //消息内容
        $rxpk = array_merge(array_pop($rxpk),$rxpk);
        if (!(Cache::has('mlog'.$rxpk['DevE']))) {
            Cache::put('mlog'.$rxpk['DevE'],true,3);
            $type = DB::table('type')->select('name','id')->where('AppEUI',$rxpk['AppE'])->first();
            if (!empty($type)) {
                $tabletype = '';
                $mark = true;
                // 获取要查询的表名称
                switch ($type['name'])
                {
                    case '烟感':
                        $tabletype = 'smoke';
                        break;
                    case '红外':
                        $tabletype = 'infrared';
                        break;
                    case '呼救':
                        $tabletype = 'help';
                        break;
                    case '燃气':
                        $tabletype = 'gas';
                        break;
                    case '电气':
                        $tabletype = 'electric';
                        break;
                    default:
                        $mark = false;
                }
                if ($mark) {
                    $where = array();
                    $where['tb.DevEUI'] = $rxpk['DevE'];
                    // 查询设备信息
                    $raw = DB::table($tabletype.' as tb')
                        -> leftJoin('room as r','tb.room_id','=','r.id')
                        -> leftJoin('building as b','r.building_id','=','b.id')
                        -> leftJoin('area as a','b.area_id','=','a.id')
                        -> leftJoin('model as m','tb.model_id','=','m.id')
                        -> leftJoin('camera as c','tb.camera_id','=','c.id')
                        -> select('tb.num','tb.agent_id','tb.DevEUI','tb.status','tb.room_id','tb.loc','r.name as rname','r.building_id','b.name as bname','b.latitude','b.longitude','b.area_id','a.name as aname','m.parse','c.url')
                        -> where($where)
                        -> first();
                    /*tbs-110 b18008ff0000e1
                    $preg = [
                        [
                            'From'=>0,
                            'To'=>2,
                            'Type'=>'enum',
                            'enum'=>[
                                'b1'=>'warn'
                                'b2'=>'warn'
                            ]
                        ],
                        [
                            'From'=>6,
                            'To'=>2,
                            'Type'=>'numerical',
                            "prefix"=>"温度:",
                            "suffix"=>"℃"
                        ],
                        [
                            'From'=>3,
                            'To'=>3,
                            'Type'=>'eachtoenum',
                            'prefix'=>'告警',
                            'eachtoenum'=>[
                                ['火灾','故障','低电量','底座温度超限'],
                                ['自检',3=>'防拆'],
                                ['底座与烟感失联','底座温度传感器故障','底座低电压','其他故障']
                            ]
                        ]
                    ];
                    tbs-100 a1d815ffe1
                    $preg = [
                        [
                            'From'=>0,
                            'To'=>2,
                            'Type'=>'enum',
                            'enum'=>[
                                'a1'=>'warn',
                                'a2'=>'warn'
                            ]
                        ],
                        [
                            'From'=>4,
                            'To'=>2,
                            'Type'=>'numerical',
                            "prefix"=>"温度:",
                            "suffix"=>"℃"
                        ],
                        [
                            'From'=>3,
                            'To'=>1,
                            'Type'=>'eachtoenum',
                            'prefix'=>'告警',
                            'eachtoenum'=>[
                                ['火灾','故障','低电量','温度']
                            ]
                        ]
                    ];
                    豪恩
                    $preg = [
                        [
                            'From'=>0,
                            'To'=>2,
                            'Type'=>'enum',
                            'enum'=>[
                                'fa'=>'msg'
                            ]
                        ],
                        [
                            'From'=>-4,
                            'To'=>2,
                            'Type'=>'numerical',
                            "prefix"=>"电量:",
                            "suffix"=>"%"
                        ],
                        [
                            'From'=>-6,
                            'To'=>2,
                            'Type'=>'eachtoenum',
                            'prefix'=>'告警',
                            'eachtoenum'=>[
                                [1=>'电压','防拆','告警'],
                                ['故障','类型']
                            ]
                        ]
                    ];
                    dd(json_encode($preg));*/
                    // 如果设备存在
                    if ($raw) {
                        if ($raw['status'] == 1) { 
                            $pregJson = Storage::get($raw['parse']);
                            $preg = json_decode($pregJson,true);
                            // 解析数据
                            $msg = $this->analysis($rxpk['datar'],$preg);
                            // 判断数据格式是否正确
                            if ($msg[0]=='msg') {
                                // 当为心跳时
                                $msgdata = $raw;
                                $msgdata['type'] = $type['name'];
                                if ( empty($msg[2]) ) {
                                    $msgdata['genre'] = '心跳';
                                } else {
                                    // 当为报警信息
                                    if(strrchr($msg[2],'、') == null){
                                        $msgdata['genre'] = $msg[2];
                                    }else {
                                        $msgdata['genre'] = ltrim(strrchr($msg[2], '、'), '、');
                                    }
                                    $users = array();
                                    $busers = array();
                                    $users['bemail'] = array();
                                    $users['bphone'] = array();
                                    $users['bmobile'] = array();
                                    $noti = DB::table('noti_set')->get();
                                    // 获取用户信息
                                    // $area = Area::where('id',$raw['area_id'])->first()->member()->orderBy('name')->get();
                                    $area = Area::where('id',$raw['area_id']) -> first();
                                    if ( (!empty($area)) && (!empty($area->member)) ){
                                        foreach ($area->member as $areaUsers) {
                                            if ($areaUsers->name) {
                                                array_push($busers,$areaUsers->name);
                                            }
                                            // 邮箱
                                            if (($noti['2']['noti_area']==1)&&($areaUsers->email)) {
                                                array_push($users['bemail'],$areaUsers->email);
                                            }
                                            // 短信
                                            if (($noti['0']['noti_area']==1)&&($areaUsers->phone)) {
                                                array_push($users['bphone'],$areaUsers->phone);
                                            }
                                            // 语音
                                            if (($noti['1']['noti_area']==1)&&($areaUsers->phone)) {
                                                array_push($users['bmobile'],$areaUsers->phone);
                                            }
                                        } 
                                    }
                                    $building = Building::where('id',$raw['building_id'])->first();
                                    if( (!empty($building) ) && (!empty($building->member)) ) {
                                        foreach ($building->member as $buildingUsers) {
                                            if ($buildingUsers->name) {
                                                array_push($busers,$buildingUsers->name);
                                            }
                                            // 邮件
                                            if (($noti['2']['noti_building']==1)&&($buildingUsers->email)) {
                                                array_push($users['bemail'],$buildingUsers->email);
                                            }
                                            // 短信
                                            if (($noti['0']['noti_building']==1)&&($buildingUsers->phone)) {
                                                array_push($users['bphone'],$buildingUsers->phone);
                                            }
                                            // 语音
                                            if (($noti['1']['noti_building']==1)&&($buildingUsers->phone)) {
                                                array_push($users['bmobile'],$buildingUsers->phone);
                                            }
                                        }
                                    }
                                    $room = Room::where('id',$raw['room_id'])->first();
                                    if( (!empty($room)) && (!empty($room->member)) ) {
                                        foreach ($room->member as $roomUsers) {
                                            if ($roomUsers->name) {
                                                array_push($busers,$roomUsers->name);
                                            }
                                            // 邮件
                                            if (($noti['2']['noti_room']==1)&&($roomUsers->email)) {
                                                array_push($users['bemail'],$roomUsers->email);
                                            }
                                            // 短信
                                            if (($noti['0']['noti_room']==1)&&($roomUsers->phone)) {
                                                array_push($users['bphone'],$roomUsers->phone);
                                            }
                                            // 语音
                                            if (($noti['1']['noti_room']==1)&&($roomUsers->phone)) {
                                                array_push($users['bmobile'],$roomUsers->phone);
                                            }
                                        }
                                    }

                                    // workerman
                                    $msgdata['user'] = array_pop($busers);
                                    $userphone = $users['bphone'];
                                    // $msgdata['phone'] = substr_replace(array_pop($userphone),"****",3,4);
                                    $msgdata['phone'] = array_pop($userphone);
                                    $data_json = json_encode($msgdata);
                                    unset($msgdata['user'],$msgdata['phone']);
                                    // 指明给谁推送，为空表示向所有在线用户推送
                                    $to_uid = "new";
                                    // 推送的url地址，使用自己的服务器地址
                                    $push_api_url = "http://lot.iqykj.com:2121/";
                                    $post_data = array(
                                       "type" => "publish",
                                       "content" => $data_json,
                                       "to" => $to_uid,
                                    );
                                    $ch = curl_init ();
                                    curl_setopt ( $ch, CURLOPT_URL, $push_api_url );
                                    curl_setopt ( $ch, CURLOPT_POST, 1 );
                                    curl_setopt ( $ch, CURLOPT_HEADER, 0 );
                                    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
                                    curl_setopt ( $ch, CURLOPT_POSTFIELDS, $post_data );
                                    curl_setopt ($ch, CURLOPT_HTTPHEADER, array("Expect:"));
                                    $return = curl_exec ( $ch );
                                    curl_close ( $ch );
                                    var_export($return);
                                    
                                    // 通知
                                    Event::fire(new Inform($msgdata,$users,$noti));
                                }

                                // 温度|明暗信息
                                if (!empty($msg[1])) {
                                    $msgdata['degree'] =  $msg[1];
                                } else {
                                    $msgdata['degree']  = '';
                                }

                                // 全部消息
                                $msgdata['time'] = $rxpk['tmst'];
                                (int)$number = $rxpk['lsnr']*100;
                                if( $number < -1000 ){
                                    $msgdata['lsnr'] = 1;
                                }elseif((-1000 <= $number) && ($number< 0)){
                                    $msgdata['lsnr'] = 2;
                                }elseif((0 <= $number) && ($number < 1000)){
                                    $msgdata['lsnr'] = 3;
                                }elseif(1000 <= $number){
                                    $msgdata['lsnr'] = 4;
                                }
                                Event::fire(new AllLog($msgdata));
                            }
                        }
                    }
                }
            }
            // debug
            Event::fire(new Debug($data));
        }
    }

    public function analysis ($datas,$preg)
    {
        $arr = [];
        if((!empty($datas))||(!empty($preg))){
            foreach ($preg as $key => $value) {
                $genre = '';
                $mark = substr($datas,$preg[$key]['From'],$preg[$key]['To']);
                // var_dump($preg[$key]['Type']);
                switch ($preg[$key]['Type']) {
                    case 'enum':
                        // 标志符
                        // $genre = $preg['mark'][$preg['mark']['Type']][$mark];
                        if(isset($preg[$key]['enum'][$mark])){
                            $genre = $preg[$key]['enum'][$mark];
                        }
                        array_push($arr,$genre);
                        break;
                    case 'numerical':
                        // 十六进制转有符号十进制
                        $scale= strtolower(substr($datas,$preg[$key]['From'],$preg[$key]['To']));
                        if(hexdec($scale)>127){
                            $number = unpack("l", pack("l", hexdec('ffffff'.$scale)))[$key];
                        } else {
                            $number = hexdec($scale);
                        }
                        if ($number!=0) {
                            $genre = $preg[$key]['prefix'].$number.$preg[$key]['suffix'];
                        }
                        array_push($arr,$genre);
                        break;
                    case 'eachtoenum':
                        // 警告解析
                        $types = '';
                        $msgdata = substr($datas,$preg[$key]['From'],$preg[$key]['To']);
                        for($i=strlen($msgdata)-1;$i>=0;$i--){
                            if(decbin(hexdec($msgdata[$i]))!=0){
                                $Binary = str_pad(decbin(hexdec($msgdata[$i])),4,'0',STR_PAD_LEFT);
                                for($r=3;$r>=0;$r--){
                                    if(isset($preg[$key]['eachtoenum'][$i][$r])){
                                        if($Binary[$r]==1){
                                            $types .= '、'.$preg[$key]['eachtoenum'][$i][$r];
                                        }
                                    }
                                }
                            }
                        }
                        $genre = ltrim($types,'、');
                        array_push($arr,$genre);
                        break;
                    default:
                        break;
                }
            }
            return $arr; 
        }
    }
}
